package com.cn.wanxi.service;

import com.cn.wanxi.dao.NavDao;
import com.cn.wanxi.model.NavModel;
import com.cn.wanxi.util.IOTool;
import com.cn.wanxi.util.Path;
import com.cn.wanxi.util.Tool;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class NavService {

    public List<NavModel> getNavArray() {
//        NavDao navDao = new NavDao();
//        int leng = navDao.hrefs.length;
//        NavModel[] navArray = new NavModel[leng];
//        for (int i = 0; i < leng; i++) {
//            NavModel model = new NavModel();
//            model.setTitle(navDao.titles[i]);
//            model.setHref(navDao.hrefs[i]);
//            navArray[i] = model;
//        }
//        数据和集合的区别？


//        String SPLIT = "";
//        1.创建文件
//        File file = IOTool.createNote(Path.PATH, Path.NAV_NAME);
//        2.写数据
//        writeNote(file);
        setNavModeArray();
//        3.读数据
        String result = IOTool.readNote();
//        4.封装
//        List<NavModel> list = new ArrayList<>();


        return setNavModelList(result);
    }

    /**
     * 封装数据用于写入记事本
     */
    private void setNavModeArray() {
        List<String> list = new ArrayList<>();
        NavDao navDao = new NavDao();
        list.add(Arrays.toString(navDao.titles));
        list.add(Arrays.toString(navDao.hrefs));
        IOTool.wirteNote(Path.NAV_NAME, list);

    }

    private List<NavModel> setNavModelList(String result) {
        String[] results = result.split(Path.SPLIT);//将分隔符分开成两个部分
        String href = results[1];//拿到连接部分
//        href = href.replace("[", "");
//        href = href.replace("]", "");
        String title = results[0];//拿到title部分
        String[] hrefs = Tool.replace(href).split(",");
        String[] titles = Tool.replace(title).split(",");
        List<NavModel> list = new ArrayList<>();
        for (int i = 0; i < hrefs.length; i++) {
            NavModel model = new NavModel();
            model.setTitle(titles[i]);
            model.setHref(hrefs[i]);
            list.add(model);
        }
        return list;
    }


    public static void main(String[] args) {
//        new NavService().getNavArray();
        System.out.println(Path.PathEnum.PATH.getAa());
    }

    private void writeNote(File file) {
        try {
            OutputStream outputStream = new FileOutputStream(file);
            NavDao navDao = new NavDao();
            String s = Arrays.toString(navDao.titles);
            System.out.println(s);
            outputStream.write(Arrays.toString(navDao.titles).getBytes());
            outputStream.write(Path.SPLIT.getBytes());
            outputStream.write(Arrays.toString(navDao.hrefs).getBytes());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
